﻿using System;
using System.Data.Entity.Core.Metadata.Edm;
using System.Windows.Forms;
using TCM.DbContextt;
using TCM.Models;
using System.Data.Entity;

namespace TCM.Forms
{
    public partial class TargetObjectList : Form
    {
        private BaseContext db;

        public TargetObjectList()
        {
            InitializeComponent();
            db = new BaseContext();
            LoadTable();
        }

        private void LoadTable()
        {
            db.TargetObjects.Load();

            dataGridView1.DataSource = db.TargetObjects.Local.ToBindingList();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            CategoriesManager objectManager = new CategoriesManager();

            var result = objectManager.ShowDialog(this);

            if (result == DialogResult.Cancel)
                return;

            TargetObject targetObject = new TargetObject();

            targetObject.TargetObjectId = Guid.NewGuid();
            targetObject.Name = objectManager.textBox1.Text;

            db.TargetObjects.Add(targetObject);

            db.SaveChanges();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int index = dataGridView1.SelectedRows[0].Index;
                Guid id = Guid.Empty;
                bool converted = Guid.TryParse(dataGridView1[0, index].Value.ToString(), out id);
                if (converted == false)
                    return;

                TargetObject targetObject = db.TargetObjects.Find(id);

                CategoriesManager objectManager = new CategoriesManager();


                objectManager.textBox1.Text = targetObject.Name;

                DialogResult result = objectManager.ShowDialog(this);

                if (result == DialogResult.Cancel)
                    return;

                targetObject.Name = objectManager.textBox1.Text;

                db.Entry(targetObject).State = EntityState.Modified;
                db.SaveChanges();

                MessageBox.Show("Объект обновлен");

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int index = dataGridView1.SelectedRows[0].Index;
                Guid id = Guid.Empty;
                bool converted = Guid.TryParse(dataGridView1[0, index].Value.ToString(), out id);
                if (converted == false)
                    return;

                TargetObject targetObject = db.TargetObjects.Find(id);
                db.TargetObjects.Remove(targetObject);
                db.SaveChanges();

                MessageBox.Show("Объект удален");
            }
        }
    }
}
